/*
 * author LIUYANLONG AMS
 * 公共的数据表格处理
 *
 * Date: 2016-11-03 08:04
 */

var editRow = undefined;//当前编辑的行
var unValidate = '数据验证不通过!';//数据验证不通过提示消息
var selectRowMsg = '请选择记录!';

if (projectName == undefined) {
    var projectName = '';
}
var queryParams = [];
var authCode = '';//权限代码

//扩展jquery函数
$.fn.serializeObject = function()   
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

/** 数据表格初始化及默认参数处理 **/
$(function () {
    authCode = getUrlParam('authCode');
    if (null == authCode || 'null' == authCode) {
        authCode = '10000000';
    }
    buttonAuthControl(authCode);
    //对象initd存在时，初始化数据表格
    if (window.initd) {
        if (jQuery.isEmptyObject(initd.dg)) {
            initd.dg = $('#dg');
            if (initd.dg.length == 0) {
                initd.dg = undefined;
            }
        }
        if (initd.pageSize == undefined) {
            initd.pageSize = 20;
        }
        initQueryParam();
        if (window.initd) {
            var head = {};
            head.dataDic =initd.dataDicList;
            queryParams['head'] = head;
        }
        //初始化Datagrid
        initAmsDatagrid();
        //初始化查询下拉条件
        initAmsSearchCombo();
    }
});

/** 根据权限代码处理隐身按钮,只有type为query的不隐藏 **/
function buttonAuthControl(authCode) {
    //第一位未1有所有权限
    if (authCode.charAt(0) == '1') {
        return;
    }
    var nodearr = $("#dg-buttons").find("a");
    nodearr.each(function (index, item) {
        if ('query' != item.type) {
            item.style.display = 'none';
        }
    });
}

/** DATAGRID增删改查操作类 **/
var dgop = {
    add: function () {/*新增*/
        if (editRow != undefined) {
            if (!initd.dg.datagrid('validateRow', editRow)) {
                $.messager.alert('提示', unValidate);
                return;
            }
            initd.dg.datagrid('unselectAll');
            initd.dg.datagrid('endEdit', editRow);
        }
        initd.dg.datagrid('insertRow', {
            index: 0,
            row: {}
        });
        initd.dg.datagrid('beginEdit', 0);
        initd.dg.datagrid('selectRow', 0);
        editRow = 0;
    },
    remove: function () {/*删除*/
        if (editRow != undefined) {
            initd.dg.datagrid('endEdit', editRow);
        }
        var rows = initd.dg.datagrid('getSelections');
        if (rows.length == 1) {
            var index = initd.dg.datagrid('getRowIndex', rows[0]);
            if (index != editRow) {
                if (!initd.dg.datagrid('validateRow', editRow)) {
                    $.messager.alert('提示', unValidate);
                    return;
                }
            }
            initd.dg.datagrid('deleteRow', index);
        } else {
            $.messager.alert('提示', selectRowMsg);
        }
    },
    edit: function () {/*修改*/
        var rows = initd.dg.datagrid('getSelections');
        if (rows.length == 1) {
            if (editRow != undefined) {
                if (!initd.dg.datagrid('validateRow', editRow)) {
                    $.messager.alert('提示', unValidate);
                    return;
                }
                initd.dg.datagrid('endEdit', editRow);
            }
            var index = initd.dg.datagrid('getRowIndex', rows[0]);
            initd.dg.datagrid('beginEdit', index);
            editRow = index;
        } else {
            $.messager.alert('提示', selectRowMsg);
        }
    },
    reject: function () {/*撤销*/
        $.messager.confirm('请确认', '撤回未保存的修改？', function (r) {
            initd.dg.datagrid('unselectAll');
            initd.dg.datagrid('rejectChanges');
            editRow = undefined;
        }
        );
    },
    copy: function () {/*复制*/
        if (editRow != undefined) {
            if (!initd.dg.datagrid('validateRow', editRow)) {
                $.messager.alert('提示', unValidate);
                return;
            }
            initd.dg.datagrid('endEdit', editRow);
        }
        var rows = initd.dg.datagrid('getSelections');
        var newRow;
        if (rows.length == 1) {
            newRow = rows[0];
            newRow.id = '';
        } else {
            $.messager.alert('提示', '请选择要复制的行!');
            return;
        }
        initd.dg.datagrid('insertRow', {
            index: 0,
            row: newRow
        });
        initd.dg.datagrid('beginEdit', 0);
        initd.dg.datagrid('selectRow', 0);
        editRow = 0;
    },
    save: function () {/*保存*/
        if (!initd.dg.datagrid('validateRow', editRow)) {
            $.messager.alert('提示', unValidate);
            return;
        }
        initd.dg.datagrid('unselectAll');
        initd.dg.datagrid('endEdit', editRow);
        var insertRows = initd.dg.datagrid('getChanges', 'inserted');
        var deleteRows = initd.dg.datagrid('getChanges', 'deleted');
        var updateRows = initd.dg.datagrid('getChanges', 'updated');

        var rows = initd.dg.datagrid('getChanges');

        for (var i = 0; i < rows.length; i++) {
            var editIndex = initd.dg.datagrid('getRowIndex', rows[0]);
            if (!initd.dg.datagrid('validateRow', editIndex)) {
                $.messager.alert('提示', '第' + editIndex + '行数据验证不通过!');
                return;
            }
        }

        //保存时的消息提醒
        var msg = '';
        if (insertRows.length > 0) {
            msg += insertRows.length + '条新增，'
        }
        if (deleteRows.length > 0) {
            msg += deleteRows.length + '条删除，'
        }
        if (updateRows.length > 0) {
            msg += updateRows.length + '条修改，'
        }
        msg += '共' + rows.length + '条变更!'

        if (rows.length == 0) {
            $.messager.alert('提示', '没有变更,不需要保存!');
            return;
        }

        $.messager.confirm('请确认', msg, function (r) {
            //调用后台更新数据
            saveData(insertRows, deleteRows, updateRows);
        }
        );

    },
    find: function () {/*使用查询框条件查询*/
        queryParams = getQueryParam();
        initd.dg.datagrid('options').queryParams = queryParams;
        initd.dg.datagrid('load');
    },
    clear: function () {/*使用查询框条件查询*/
        //组织查询条件
        var queryField = $("#dg-buttons").find("input");
        var searchKey;
        var searchValue;
        for (var i = 0; i < queryField.length; i++) {
            var temp = queryField[i].id;
            if (temp == 'searchKey') {
                searchKey = $("#dg-buttons").find("#" + temp).combobox('setValue', "");
            } else if (temp == 'searchValue') {
                searchValue = $("#dg-buttons").find("#" + temp).val("");
            } else if (temp.length > 0) {
                var className = $("#dg-buttons").find("#" + temp).attr("class");
                if (className.length > 0) {
                    if (className.indexOf("combobox") > 0) {//如果是combobox控件则用getValues函数取值，其他则用val取值
                        $("#dg-buttons").find("#" + temp).combobox('setValue', "");
                    } else {
                        $("#dg-buttons").find("#" + temp).val("");
                    }
                }
            }
        }
    }
};
/**
 * 特殊字符检测
 * @param input
 * @returns
 */
function check(input) {

    var strExp = RegExp("[\\[\\]\\%<>\\|\\&\\#\\=\\+]");

    return strExp.test(input);

}

/** DATAGRID 数据保存的处理 **/
function saveData(insertRows, deleteRows, updateRows) {
    /** if(typeof(JSON) == "undefined") **/
    if (insertRows.length > 0) {
        insertRows = JSON.stringify(insertRows);
    }
    if (deleteRows.length > 0) {
        deleteRows = JSON.stringify(deleteRows);
    }
    if (updateRows.length > 0) {
        updateRows = JSON.stringify(updateRows);
    }
    initd.dg.datagrid('loading');
    $.ajax({
        type: "POST",
        url: projectName + initd.saveDataURL,
        crossDomain:true,
        xhrFields:{
            withCredentials:true
        },
        data: {
            'insertRows': insertRows,
            'deleteRows': deleteRows,
            'updateRows': updateRows
        },
        dataType: "json",
        success: function (data) {
            if (!data.success) {
                if (!jQuery.isEmptyObject(data.message)) {
                    $.messager.alert("系统错误", data.message);
                } else {
                    $.messager.alert("系统错误", data);
                }
                return;
            }
            if (data != null) {
                initd.dg.datagrid('loaded');
                initd.dg.datagrid('reload');
            }
        },
        error: function (err, status) {
            errorMsgAlert(err);
        }
    });
}

//获取数据字典内容 刘彦龙20170331
function amsDataFilter(data) {
    if (initd.dataDicMap == undefined && data.extValues != undefined) {
        initd.dataDicMap = data.extValues.dataDicMap;
    }
    if (!jQuery.isEmptyObject(initd.dataDicList) && initd.dataDicMap == undefined) {
        $.messager.alert("系统提示", "数据字典加载错误！请检查字典定义");
    }
    if (initd.dataDicJsonMap == undefined) {
        initd.dataDicJsonMap = {};

        if (initd.dataDicLocal != undefined && !jQuery.isEmptyObject(initd.dataDicLocal)) {
            if (data.extValues == undefined) {
                data.extValues = {};
            }
            if (data.extValues.dataDicMap == undefined) {
                data.extValues.dataDicMap = {};
            }
            if (initd.dataDicList == undefined) {
                initd.dataDicList = {};
            }
            $.each(initd.dataDicLocal, function (key, value) {
                data.extValues.dataDicMap[key] = value;
                initd.dataDicList[key] = [key];
            });
            if (initd.dataDicMap == undefined) {
                initd.dataDicMap = data.extValues.dataDicMap;
            }
        }

        if (data.extValues != undefined && !jQuery.isEmptyObject(data.extValues.dataDicMap)) {
            $.each(data.extValues.dataDicMap, function (key, value) {
                if (null != value) {
                    var json = [];
                    $.each(value, function (key, value) {
                        var row = { "id": key, "text": value };
                        json.push(row);
                    });
                    initd.dataDicJsonMap[key] = json;
                }
            });
        }

    }

    initCombobox();
    return data;
}


//解析数据字典 刘彦龙20170331
function setDataDic(val, row, index, dataType) {
    if (dataType in initd.dataDicMap) {
        var map = initd.dataDicMap[dataType];
        if (null != map && val in map) {
            return map[val];
        }
        return val;
    }
    return val;
}

//新增
function dlgAdd() {
    $("#dlg").dialog({
        title: '新增信息',
        onClose: function () { resetFromValue(); }
    }).dialog("open");
}
//编辑记录
function dlgEdit() {
    var selectedRows = $("#dg").datagrid("getSelections");
    if (selectedRows.length != 1) {
        $.messager.alert("系统提示", "请选择一条要编辑的数据！");
        return;
    }
    var row = selectedRows[0];
    $("#dlg").dialog({
        title: '编辑信息',
        onClose: function () { resetFromValue(); }
    }).dialog("open");
    $("#fm").form("load", row);
}

function dlgClose() {
    $("#dlg").dialog("close");
    resetFromValue();
}

//单笔保存记录 liuyanlong 20170421
function dlgSave() {
    $.messager.progress();
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType : "application/json;charset=utf-8",
        url: projectName + initd.saveDataURL,
        crossDomain:true,
        xhrFields:{
            withCredentials:true
        },
        data: JSON.stringify($("#fm").serializeObject()),
        beforeSend: function () {
            var isValid = $("#fm").form("validate")
            if (!isValid) {
                $.messager.progress("close");
                $.messager.alert("系统提示", "表单验证不通过！");
            }
            return isValid;
        },
        success: function (result) {
            $.messager.progress("close");
            if (result.success) {
                $.messager.alert("系统提示", "提交成功！");
                resetFromValue();
                $("#dlg").dialog("close");
                $("#dg").datagrid("reload");
            } else {
                if (!jQuery.isEmptyObject(result.message)) {
                    $.messager.alert("系统错误", result.message);
                } else {
                    $.messager.alert("系统错误", result);
                }
                return;
            }
        },
        error: function (err, status) {
            $.messager.progress("close");
            errorMsgAlert(err);
        }
    });
}

function saveSimpleObj(simpleObj) {
    $.messager.progress();
    $.ajax({
        type: "POST",
        url: projectName + initd.saveDataURL,
        crossDomain:true,
        xhrFields:{
            withCredentials:true
        },
        data: simpleObj,
        dataType: "json",
        contentType : "application/json;charset=utf-8",
        success: function (data) {
            $.messager.progress("close");
            if (!data.success) {
                if (!jQuery.isEmptyObject(data.message)) {
                    $.messager.alert("系统错误", data.message);
                } else {
                    $.messager.alert("系统错误", data);
                }
                return;
            }
            if (data != null) {
                initd.dg.datagrid('loaded');
                initd.dg.datagrid('reload');
            }
        },
        error: function (err, status) {
            $.messager.progress("close");
            errorMsgAlert(err);
        }
    });
}

//单笔删除记录 liuyanlong 20170401
function dlgRemove() {
    var selectedRows = $("#dg").datagrid("getSelections");
    if (selectedRows.length == 0) {
        $.messager.alert("系统提示", "请选择要删除的数据！");
        return;
    }
    var removeData = selectedRows[0]
    if (selectedRows.length > 1) {
        removeData = {
            'deleteRows': deleteRows,
        }
    }

    $.messager.confirm("系统提示", "您确定要删除这<font color=red>" + selectedRows.length + "</font>条数据吗？", function (r) {
        if (r) {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: projectName + initd.removeDataURL,
                crossDomain:true,
                xhrFields:{
                    withCredentials:true
                },
                data: JSON.stringify(removeData),
                contentType : "application/json;charset=utf-8",
                beforeSend: function () {
                },
                success: function (result) {
                    $.messager.progress("close");
                    if (result.success) {
                        $.messager.alert("系统提示", "数据已成功删除！");
                        $("#dg").datagrid("reload");
                    } else {
                        if (!jQuery.isEmptyObject(result.message)) {
                            $.messager.alert("系统错误", result.message);
                        } else {
                            $.messager.alert("系统错误", result);
                        }
                        return;
                    }
                },
                error: function (err, status) {
                    $.messager.progress("close");
                    errorMsgAlert(err);
                }
            });

        }
    });
}

//值空form表单中缓存的值
function resetFromValue() {
    $("#fm").find("input").val("");
}

//初始化from表单中的枚举下拉框 liuyanlong
function initCombobox() {
    if (isEmptyDataGrid()) {
        return;
    }
    if (!jQuery.isEmptyObject(initd.dataDicList) && !jQuery.isEmptyObject(initd.dataDicJsonMap)) {
        for (var dataType in initd.dataDicList) {
            for (var i = 0; i < initd.dataDicList[dataType].length; i++) {
                var field = initd.dataDicList[dataType][i]
                //定义的column
                if (!jQuery.isEmptyObject(initd.dg)) {
                    var columnOp = $("#dg").datagrid('getColumnOption', field);
                    if (!jQuery.isEmptyObject(columnOp)) {
                        //字段格式化函数 , 解析码值 
                        var fmtfunction = new Function('value', 'row', 'index', "return setDataDic(value,row,index,'" + dataType + "');");
                        columnOp.formatter = fmtfunction;
                    }
                }

                try {
                    $("#dlg").find("#" + field).combobox({
                        data: initd.dataDicJsonMap[dataType],
                        valueField: 'id',
                        textField: 'text'
                    });
                } catch (e) {
                    //IE8莫名报错
                }
                $("#dg-buttons").find("#" + field).combobox({
                    data: initd.dataDicJsonMap[dataType],
                    valueField: 'id',
                    textField: 'text'
                });
            }
        }
    }

}

function errorMsgAlert(err) {
    $.messager.alert("错误提示", '[' + err.status + ']' + err.responseText);
}

//获取URL参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

//初始化查询下拉条件
function initAmsSearchCombo() {
    if (isEmptyDataGrid()) {
        return;
    }
    var searchKey = $("#dg-buttons").find("#searchKey");
    if (!jQuery.isEmptyObject(searchKey) && searchKey.length > 0) {
        //循环列名，生成搜索的下拉列表   
        var fields = $('#dg').datagrid('getColumnFields');
        var menuData = new Array();
        for (var i = 0; i < fields.length; i++) {
            var opts = $('#dg').datagrid('getColumnOption', fields[i]);
            var node = {};
            node.id = fields[i];
            node.text = opts.title;
            menuData.push(node);
        };

        $("#searchKey").combobox({
            data: menuData,
            valueField: 'id',
            textField: 'text'
        });
    }
}

//判断 DataGrid 是否存在
function isEmptyDataGrid() {
    return typeof (initd) == 'undefined' || jQuery.isEmptyObject(initd) || typeof (initd.dg) == 'undefined' || initd.dg.length == 0;
}

//页面加载完成初始化datagrid add by liuyanlong
function initAmsDatagrid() {
    if (isEmptyDataGrid()) {
        return;
    }
    if (jQuery.isEmptyObject(initd.dg)) {
        return;
    }
    var dgClassName = initd.dg.attr('class');
    //说明datagrid已经初始化
    if (dgClassName != undefined && dgClassName.indexOf("datagrid") >= 0) {
        return;
    }

    initd.dg.datagrid({
        url: projectName + initd.queryDataURL,
        method: 'post',
        iconCls: 'icon-search',
        striped: true,
        nowrap: true,
        border: true,
        idField: 'id',
        singleSelect: true,
        rownumbers: true,
        fit: false,
        fitColumns: true,
        loadMsg: '数据加载中……',
        toolbar: '#dg-buttons',
        onClickRow: initd.onClickRow,
        pagination: true,
        pageNumber: 1,
        pageList: [10, 20, 30, 50, 100],
        pageSize: initd.pageSize,
        queryParams: queryParams,
        loadFilter: amsDataFilter,
        loader: function(param, success, error) {
            var loaderpager = initd.dg.datagrid('getPager')
            if (!jQuery.isEmptyObject(loaderpager)){
                var optionsParam = loaderpager.data('pagination').options;
                param.head.page = optionsParam.pageNumber;
                param.head.rows = optionsParam.pageSize;
            }
			$.ajax({
				type: "POST",
			    url: projectName + initd.queryDataURL,
                crossDomain:true,
                xhrFields:{
                    withCredentials:true
                },
			    data: JSON.stringify(param),
			    dataType: "json",
                contentType : "application/json;charset=utf-8",
			    success: function(data) {
			    	$.messager.progress("close");
                    if (!data.success) {
                        $.messager.alert("错误提示", '[' + data.code + ']' + data.message);
                        return;
                    }
			        success(data);
			    },
			    error: function (err, status) {
                    $.messager.progress("close");
                	$.messager.alert("错误提示", '[' + err.status + ']' + err.responseText);
                    initd.dg.datagrid('loaded');
                }
			});
        },
        onLoadSuccess: function (data) {
            $.messager.progress("close");
            rememberQueryParam();
        },
        onLoadError: function (err) {
            $.messager.progress("close");
            errorMsgAlert(err);
        }
    });

    /** DATAGRID 分页工具栏及分页查询 **/
    var pager = initd.dg.datagrid('getPager');
    $(pager).pagination({
        loading: true,
        beforePageText: '第',
        afterPageText: '页  共{pages}页',
        displayMsg: '显示条数{from}~{to},共{total}条记录'
    });
}

function dgReload() {
    $("#dg").datagrid("reload");
}

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, // month  
        "d+": this.getDate(), // day  
        "h+": this.getHours(), // hour  
        "m+": this.getMinutes(), // minute  
        "s+": this.getSeconds(), // second  
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter  
        "S": this.getMilliseconds()
        // millisecond  
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};

//初始化查询条件
function initQueryParam() {
    //组织查询条件
    var queryField = $("#dg-buttons").find("input");
    var searchKey;
    var searchValue;
    for (var i = 0; i < queryField.length; i++) {
        var temp = queryField[i].id;
        if (temp == 'searchKey') {
            searchKey = $("#dg-buttons").find("#" + temp).combobox('getValue');
            queryParams['searchKey'] = searchKey;
        } else if (temp == 'searchValue') {
            searchValue = $("#dg-buttons").find("#" + temp).val();
            queryParams['searchValue'] = searchValue;
        } else if (temp.length > 0) {
            var className = $("#dg-buttons").find("#" + temp).attr("class");
            if (className.length > 0) {
                if (className.indexOf("combobox") > 0) {//如果是combobox控件则用getValues函数取值，其他则用val取值
                    queryParams[temp] = $("#dg-buttons").find("#" + temp).combobox('getValue');
                } else {
                    queryParams[temp] = $("#dg-buttons").find("#" + temp).val();
                }
            }
        }
    }
    //实现下拉字段条件
    if (!jQuery.isEmptyObject(searchKey) && !jQuery.isEmptyObject(searchValue)) {
        queryParams[searchKey] = searchValue;
    }
}

function rememberQueryParam() {
    //组织查询条件
    var queryField = $("#dg-buttons").find("input");
    var searchKey;
    var searchValue;
    for (var i = 0; i < queryField.length; i++) {
        var temp = queryField[i].id;
        if (temp == 'searchKey') {
            searchKey = $("#dg-buttons").find("#" + temp).combobox('setValue', queryParams['searchKey']);
        } else if (temp == 'searchValue') {
            searchValue = $("#dg-buttons").find("#" + temp).val(queryParams['searchValue']);
        } else if (temp.length > 0) {
            var className = $("#dg-buttons").find("#" + temp).attr("class");
            if (className.length > 0) {
                if (className.indexOf("combobox") > 0) {//如果是combobox控件则用getValues函数取值，其他则用val取值
                    $("#dg-buttons").find("#" + temp).combobox('setValue', queryParams[temp]);
                } else {
                    $("#dg-buttons").find("#" + temp).val(queryParams[temp]);
                }
            }
        }
    }
}

function getQueryParam() {
    var queryField = $("#dg-buttons").find("input");
    var searchKey;
    var searchValue;
    for (var i = 0; i < queryField.length; i++) {
        var temp = queryField[i].id;
        if (temp == 'searchKey') {
            searchKey = $("#dg-buttons").find("#" + temp).combobox('getValue');
            queryParams['searchKey'] = searchKey;
        } else if (temp == 'searchValue') {
            searchValue = $("#dg-buttons").find("#" + temp).val();
            queryParams['searchValue'] = searchValue;
        } else if (temp.length > 0) {
            var className = $("#dg-buttons").find("#" + temp).attr("class");
            if (className.length > 0) {
                if (className.indexOf("combobox") > 0) {//如果是combobox控件则用getValues函数取值，其他则用val取值
                    queryParams[temp] = $("#dg-buttons").find("#" + temp).combobox('getValue');
                } else {
                    queryParams[temp] = $("#dg-buttons").find("#" + temp).val();
                }
            }
        }
    }
    //实现下拉字段条件
    if (!jQuery.isEmptyObject(searchKey) && !jQuery.isEmptyObject(searchValue)) {
        queryParams[searchKey] = searchValue;
    }
    return queryParams;
}

function dlgExport() {
    ajaxLoading();
    //ajax发送查询请求（根据条件查询）
    var url = projectName + initd.queryDataURL;
    queryParams = getQueryParam();
    var queryStr = {}
    for (key in queryParams) {
        queryStr[key] = queryParams[key];
    }

    //获取datagrid的表头字段
    var colValue = $("#dg").datagrid('getColumnFields');
    //定义title数组，存储title
    var colTitle = new Array();
    for (var i = 0; i < colValue.length; i++) {
        var fid = $("#dg").datagrid('getColumnOption', colValue[i]);
        var value = fid.title
        colTitle[i] = value;
    }
    queryStr['columnTitle'] = colTitle;
    queryStr['columnValue'] = colValue;
    //model=expall，导出excel
    queryStr.head.model = 'expall';
    queryStr.head.page = 1;
    queryStr.head.rows = 5000;
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType : "application/json;charset=utf-8",
        url: url,
        crossDomain:true,
        xhrFields:{
            withCredentials:true
        },
        data: JSON.stringify(queryStr),
        success: function (result) {
            if (result.success) {
                downloadFile(result.entity)
            } else {
                if (!jQuery.isEmptyObject(result.message)) {
                    $.messager.alert("系统错误", result.message);
                } else {
                    $.messager.alert("系统错误", result);
                }
                return;
            }
            ajaxLoadEnd()
        },
        error: function (err, status) {
            ajaxLoadEnd()
            errorMsgAlert(err);
        }
    });
    ajaxLoadEnd();
}

//下载文件
function downloadFile(fileName) {
    try {
        var options = { 'fileName': fileName, 'tempdir': "true" }
        var index = options.fileName.lastIndexOf('/')
        if (index === -1) {
            index = options.fileName.lastIndexOf('\\')
        }
        var fileName = options.fileName.substring(index + 1)
        var req = new XMLHttpRequest();
        req.open('POST', projectName + "/downloadfile", true);
        req.responseType = 'blob';
        req.setRequestHeader('Content-Type', 'application/json');
        req.onload = function() {
            var data = req.response;
            var a = document.createElement('a');
            var blob = new Blob([data]);
            var blobUrl = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.style.display = 'none';
            a.download = fileName;
            a.href = blobUrl;
            a.click();
        };
        req.send(JSON.stringify(options));

    } catch (e) {
        console.log(e);
    }
}

//设置juery easyUI loading css
function ajaxLoading() {
    $("<div class=\"datagrid-mask\"></div>").css({ display: "block", width: "100%", height: $(window).height() }).appendTo("body");
    $("<div class=\"datagrid-mask-msg\"></div>").html("正在打印，请稍后。。。。。").appendTo("body").css({ display: "block", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 });
}

//loading 结束
function ajaxLoadEnd() {
    $(".datagrid-mask").remove();
    $(".datagrid-mask-msg").remove();
}

function getDateStr8() {
    var temptoday = new Date();
    var year = temptoday.getFullYear();
    var month = temptoday.getMonth() + 1;
    var fullmonth = "";
    if (month >= 0 && month <= 9) {
        month = "0" + month;
    }
    var day = temptoday.getDate();
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    return "" + year + month + day;
}

